package com.tao.plan.controller;


import cn.hutool.core.bean.BeanUtil;
import com.tao.plan.common.BaseThreadLocal;
import com.tao.plan.common.R;
import com.tao.plan.domain.pojo.PCountDownDay;
import com.tao.plan.domain.vo.CountDownDayVo;
import com.tao.plan.service.PCountDownDayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/countDownDay")
public class CountDownDayController {

	@Autowired
	private PCountDownDayService pCountDownDayService;
	/**
	 * 新增
	 */
	@PostMapping("/add")
	public R add(@RequestBody PCountDownDay countDownDay){
		countDownDay.setUid(Long.valueOf(BaseThreadLocal.getUid()));
		pCountDownDayService.save(countDownDay);
		return R.build().success();
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	public R update(@RequestBody PCountDownDay countDownDay){
		pCountDownDayService.updateById(countDownDay);
		return R.build().success();
	}
	/**
	 * 删除
	 */
	@DeleteMapping("/delete/{id}")
	public R delete(@PathVariable("id") Long id){
		pCountDownDayService.removeById(id);
		return R.build().success();
	}

	/**
	 * 查询
	 */
	@GetMapping("/list/{status}")
	public R list(@PathVariable("status") Integer status){
		List<PCountDownDay> list = pCountDownDayService.listByDateTime(status);
		List<CountDownDayVo> collect = list.stream().map(item -> {
			LocalDateTime targetTime = item.getTargetTime();
			LocalDate now = LocalDate.now();
			LocalDate targetDate = targetTime.toLocalDate();
			long daysBetween = ChronoUnit.DAYS.between(now, targetDate);
			CountDownDayVo countDownDayVo = new CountDownDayVo();
			BeanUtil.copyProperties(item, countDownDayVo);
			countDownDayVo.setNextDays(daysBetween);
			return countDownDayVo;
		}).collect(Collectors.toList());
		return R.build().success().put("data",collect);
	}
}
